package com.cloud.messenger.configuration;

import com.cloud.messenger.MessengerTemplate;
import com.cloud.messenger.client.LocalMessageClient;
import com.cloud.messenger.client.MailMessageClient;
import com.cloud.messenger.client.MessengerClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Configuration
@ConditionalOnMissingBean(MessengerClient.class)
public class MessengerAutoConfiguration {


    @Autowired
    private MessengerConfiguration configuration;

    /**
     * 本地消息
     * @return
     */
    @Bean
    public List<LocalMessageClient> localMessageClient() {
        return configuration.getLocal().stream().filter(local -> local.getEnable()).map(local -> {
            LocalMessageClient localMessageClient = new LocalMessageClient();
            localMessageClient.setClient(local.getClient());
            localMessageClient.setLocalProperties(local);
            return localMessageClient;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    /**
     * 邮件消息
     * @return
     */
    @Bean
    public List<MailMessageClient> mailMessageClient() {
        return configuration.getMail().stream().filter(mailProperties-> mailProperties.getEnable()).map(mailProperties -> {
            MailMessageClient mailMessageClient = new MailMessageClient();
            mailMessageClient.setClient(mailProperties.getClient());
            mailMessageClient.setMailProperties(mailProperties);
            return mailMessageClient;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    /**
     * 信息模板
     */
    @Bean
    public MessengerTemplate getMessageSenderTemplate(
            List<List<? extends MessengerClient>> messageClientList
    ) {
        MessengerTemplate messengerTemplate=new MessengerTemplate();
        messengerTemplate.setMessageClientList(messageClientList);
        messengerTemplate.setMessageConfiguration(configuration);
        return messengerTemplate;
    }
}
